package com.pirestupppai.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.audiofx.Equalizer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import com.pirestupppai.R;
import com.pirestupppai.base.BaseActivity;
import com.pirestupppai.common.Constant;
import com.pirestupppai.utils.Utils;

import java.text.SimpleDateFormat;

import butterknife.BindView;

/**
 * 视频预览
 * author: xiaoluo
 * date: 2017/5/18 15:45
 */
public class VideoPreviewActivity extends BaseActivity {
    private final static String TAG = VideoPreviewActivity.class.getSimpleName();

    private static final int TIME_PROGRESS = 110;

    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.record_next)
    ImageView nextBtn;
    @BindView(R.id.old_layout)
    FrameLayout oldLayout;
    @BindView(R.id.new_layout)
    FrameLayout newLayout;
    @BindView(R.id.old_video)
    VideoView oldVideoView;
    @BindView(R.id.new_video)
    VideoView newVideoView;
    @BindView(R.id.bottom_layout)
    LinearLayout bottomLayout;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.sound_layout)
    LinearLayout soundLayout;
    @BindView(R.id.change_layout)
    LinearLayout changeLayout;
    @BindView(R.id.equalizer_layout)
    RelativeLayout equalizerLayout;
    @BindView(R.id.control_layout)
    RelativeLayout controlLayout;
    @BindView(R.id.play_btn)
    ImageView playBtn;
    @BindView(R.id.time_bar)
    SeekBar timeBar;
    @BindView(R.id.time_tv)
    TextView timeTv;
    @BindView(R.id.mine_sound_seekbar)
    SeekBar mineSoundSb;
    @BindView(R.id.old_sound_seekbar)
    SeekBar oldSoundSb;
    @BindView(R.id.low_seekbar)
    SeekBar lowSb;
    @BindView(R.id.high_seekbar)
    SeekBar highSb;

    private String mOldPath;                 // 原视频路径
    private String mNewPath;                 // 录制视频路径
    private int mReleaseType;                // 发布类型
    private String mVideoImage;              // 视频第一帧
    private int mCurrentTime = 0;

    private MediaPlayer mOldMediaPlayer;     // 原视频播放器
    private MediaPlayer mNewMediaPlayer;     // 录制视频播放器
    private Equalizer mEqualizer;            // 均衡器
    private short mMinEQlevel;               // 均衡器最小值
    private short mMaxEQlevel;               // 均衡器最大值
    private short mLowBand;
    private short mHighBand;

    @Override
    protected Context getActivityContext() {
        return this;
    }

    @Override
    protected int loadParentLayout() {
        return R.layout.activity_video_preview;
    }

    @Override
    protected void initViews() {
        Bundle bundle = getIntent().getExtras();
        mNewPath = bundle.getString(Constant.IntentKey.VIDEO_PATH);
        mReleaseType = bundle.getInt(Constant.IntentKey.RELEASE_TYPE, Constant.SELETC_TYPE_VIDEO_WORK);
        mVideoImage = bundle.getString(Constant.IntentKey.VIDEO_IMG);

//        mOldPath = "android.resource://" + getPackageName() + "/" + R.raw.aa;
//        mNewPath = "android.resource://" + getPackageName() + "/" + R.raw.bb;

        initLayoutParams();

        if (!TextUtils.isEmpty(mOldPath) && !TextUtils.isEmpty(mNewPath)) {
            oldVideoView.setVideoPath(mOldPath);
            newVideoView.setVideoPath(mNewPath);
        }


        tabLayout.addTab(tabLayout.newTab().setText("声音"), true);
        tabLayout.addTab(tabLayout.newTab().setText("变声"));
        tabLayout.addTab(tabLayout.newTab().setText("均衡器"));

//        tabLayout.post(new Runnable() {
//            @Override
//            public void run() {
//                TabLayoutHelper.setIndicatorWidth(tabLayout, 60, 60);
//            }
//        });
    }

    /**
     * 初始化布局
     */
    private void initLayoutParams() {
        RelativeLayout.LayoutParams newParams = (RelativeLayout.LayoutParams) newLayout.getLayoutParams();
        newParams.width = Constant.WIDTH_OF_SCREEN / 2;
        newParams.height = Constant.WIDTH_OF_SCREEN;
        newLayout.setLayoutParams(newParams);

        RelativeLayout.LayoutParams oldParams = (RelativeLayout.LayoutParams) oldLayout.getLayoutParams();
        oldParams.width = Constant.WIDTH_OF_SCREEN / 2;
        oldParams.height = Constant.WIDTH_OF_SCREEN;
        oldLayout.setLayoutParams(oldParams);

        FrameLayout.LayoutParams oldVideoParams = (FrameLayout.LayoutParams) oldVideoView.getLayoutParams();
        oldVideoParams.width = Constant.WIDTH_OF_SCREEN;
        oldVideoParams.height = Constant.WIDTH_OF_SCREEN;
        oldVideoParams.leftMargin = -Constant.WIDTH_OF_SCREEN / 4;
        oldVideoView.setLayoutParams(oldVideoParams);

        FrameLayout.LayoutParams newVideoParams = (FrameLayout.LayoutParams) newVideoView.getLayoutParams();
        newVideoParams.width = Constant.WIDTH_OF_SCREEN;
        newVideoParams.height = Constant.WIDTH_OF_SCREEN;
        newVideoParams.rightMargin = -Constant.WIDTH_OF_SCREEN / 2;
        newVideoView.setLayoutParams(newVideoParams);
        newVideoView.setPadding(-Utils.dpToPx(mContext, Constant.WIDTH_OF_SCREEN / 2), 0, Utils.dpToPx(mContext, Constant.WIDTH_OF_SCREEN / 2), 0);

        RelativeLayout.LayoutParams bottomParams = (RelativeLayout.LayoutParams) bottomLayout.getLayoutParams();
        bottomParams.width = Constant.WIDTH_OF_SCREEN;
        bottomParams.height = Constant.HEIGHT_OF_SCREEN - Constant.WIDTH_OF_SCREEN - Constant.HEIGHT_OF_STATUSBAR - (int) getResources().getDimension(R.dimen.titlebar_height) * 2;
        bottomLayout.setLayoutParams(bottomParams);

        RelativeLayout.LayoutParams controlLp = (RelativeLayout.LayoutParams) controlLayout.getLayoutParams();
        controlLp.width = Constant.WIDTH_OF_SCREEN;
        controlLp.height = Constant.WIDTH_OF_SCREEN;
        controlLayout.setLayoutParams(controlLp);
    }

    @Override
    protected void initListeners() {
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                changeBottomViews(tab);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putInt(Constant.IntentKey.RELEASE_TYPE, mReleaseType);
                bundle.putString(Constant.IntentKey.VIDEO_PATH, mNewPath);
                bundle.putString(Constant.IntentKey.VIDEO_IMG, mVideoImage);
                intent.putExtras(bundle);
                intent.setClass(mContext, ReleaseActivity.class);
                startActivity(intent);
                finish();
            }
        });

        oldVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                oldVideoView.start();
            }
        });

        oldVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mOldMediaPlayer = mp;
                oldVideoView.start();
            }
        });

        newVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                newVideoView.start();
                oldVideoView.seekTo(0);
            }
        });

        newVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                newVideoView.start();
                mNewMediaPlayer = mp;

                // 均衡器设置
                initEqualizer();

                // 时间进度控制条设置
                SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
                timeBar.setMax(newVideoView.getDuration());
                timeBar.setProgress(newVideoView.getCurrentPosition());
                timeTv.setText(formatter.format(newVideoView.getDuration()));
                mHandler.sendEmptyMessage(TIME_PROGRESS);
            }
        });



        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playBtn.setVisibility(View.GONE);
                oldVideoView.start();
                newVideoView.start();
            }
        });

        controlLayout.setOnClickListener(stopListener);

        timeBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {


            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                if (progress <= oldVideoView.getDuration()) {
                    oldVideoView.seekTo(progress);
                } else {
                    oldVideoView.seekTo(oldVideoView.getDuration());
                }
                newVideoView.seekTo(progress);
            }
        });


        mineSoundSb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mNewMediaPlayer.setVolume((float) seekBar.getProgress() / (float) seekBar.getMax(), (float) seekBar.getProgress() / (float) seekBar.getMax());
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        oldSoundSb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mOldMediaPlayer.setVolume((float) seekBar.getProgress() / (float) seekBar.getMax(), (float) seekBar.getProgress() / (float) seekBar.getMax());
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        lowSb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mEqualizer.setBandLevel(mLowBand, (short) (seekBar.getProgress() + mMinEQlevel));
            }
        });

        highSb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mEqualizer.setBandLevel(mHighBand, (short) (seekBar.getProgress() + mMinEQlevel));
            }
        });
    }

    /**
     * 初始化均衡器
     */
    private void initEqualizer() {
        mEqualizer = new Equalizer(0, mNewMediaPlayer.getAudioSessionId());
        mEqualizer.setEnabled(true);
        mMinEQlevel = mEqualizer.getBandLevelRange()[0];
        mMaxEQlevel = mEqualizer.getBandLevelRange()[1];
        short bandCount = mEqualizer.getNumberOfBands();

        mLowBand = mEqualizer.getBand(1000 * 1000);
        mHighBand = mEqualizer.getBand(5000 * 1000);
        lowSb.setMax(mMaxEQlevel - mMinEQlevel);
        highSb.setMax(mMaxEQlevel - mMinEQlevel);
        lowSb.setProgress(mEqualizer.getBandLevel(mLowBand) - mMinEQlevel);
        highSb.setProgress(mEqualizer.getBandLevel(mHighBand) - mMinEQlevel);
    }

    private View.OnClickListener stopListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            oldVideoView.pause();
            newVideoView.pause();
            playBtn.setVisibility(View.VISIBLE);
        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TIME_PROGRESS:
                    int currentTime = newVideoView.getCurrentPosition();
                    timeBar.setProgress(currentTime);
                    Log.d(TAG, "---" + currentTime);
                    if (!isDestroyed()) {
                        mHandler.sendEmptyMessageDelayed(TIME_PROGRESS, 1000);
                    }
                    break;
            }
        }
    };

    private void changeBottomViews(TabLayout.Tab tab) {
        if (tab.getText().equals("声音")) {
            soundLayout.setVisibility(View.VISIBLE);
            changeLayout.setVisibility(View.GONE);
            equalizerLayout.setVisibility(View.GONE);
        } else if (tab.getText().equals("变声")) {
            soundLayout.setVisibility(View.GONE);
            changeLayout.setVisibility(View.VISIBLE);
            equalizerLayout.setVisibility(View.GONE);
        } else {
            soundLayout.setVisibility(View.GONE);
            changeLayout.setVisibility(View.GONE);
            equalizerLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void initLogic() {

    }

    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler = null;
    }
}
